import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from "@angular/common/http";
import {Observable} from "rxjs/internal/Observable";
import {TokenService} from "./token.service";
import {AppModule} from "./app.module";
import {of} from "rxjs/internal/observable/of";
import {finalize, tap} from "rxjs/operators";


@Injectable({
  providedIn: 'root'
})
export class HttpTokenService implements HttpInterceptor {

  constructor(private tokenService: TokenService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let ok: string;
    if (!request.url.startsWith(AppModule.BASE_NET_URL + "/auth/login")) {

      request = request.clone({
        headers: request.headers.set('Authorization', 'Bearer ' + localStorage.getItem('token'))
      });
    }
    return next.handle(request).pipe(tap(
      // Succeeds when there is a response; ignore other events
      event => ok = event instanceof HttpResponse ? 'succeeded' : '',
      // Operation failed; error is an HttpErrorResponse
      error => ok = 'failed'
      ),
      // Log when response observable either completes or errors
      finalize(() => {
        // const elapsed = Date.now() - started;
        // const msg = `${req.method} "${req.urlWithParams}"
        //      ${ok} in ${elapsed} ms.`;
        // this.messenger.add(msg);
        if (ok == 'failed') {
          this.tokenService.getToken();
        }
      }));
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      // this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

}
